<template>
  <div>
    <Category :scene="scene" />
    <!-- 三级分类全局组件 -->
    <el-card style="margin: 10px 0;">
      <div v-show="scene == 0">
        <el-button @click="addAttr" type="primary" icon="Plus"
          :disabled="categoryStore.c3Id ? false : true">添加属性</el-button>
        <el-table border style="margin: 10px 0;" :data="attrArr">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="120px"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag style="margin: 5px;" v-for="(item, index) in row.attrValueList" :key="item.id">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row, $index }">
              <el-button @click="updateAttr(row)" type="primary" size="small" icon="Edit"></el-button>
              <el-popconfirm icon="Delete" @confirm="deleteAttr(row.id)" :title="`你确定删除${row.attrName}?`" width="200px">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <!-- 展示添加修改属性 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input v-model="attrParams.attrName" placeholder="请你输入属性名称"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addAttrValue" :disabled="attrParams.attrName ? false : true" type="primary"
          icon="Plus">添加属性值</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-table :data="attrParams.attrValueList" border style="margin: 10px 0;">
          <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row, $index)"
                size="small" placeholder="请你输入属性值名称" v-model="row.valueName"></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{ row, index }">
              <el-button type="primary" @click="attrParams.attrValueList.splice(index, 1)" size="small"
                icon="Delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" :disabled="attrParams.attrValueList.length > 0 ? false : true"
          @click="save">保存</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>

</template>

<script setup lang="ts">
import useCategoryStore from '@/store/modules/category';
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr';
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type';
import { ElMessage } from 'element-plus';

// 获取分类仓库
let categoryStore = useCategoryStore()
// 村粗已有的属性与属性值
let attrArr = ref<Attr[]>([])
// 定义card组件内容切换的变量
let scene = ref<number>(0) //scene=0显示table,scene=1展示添加与修改属性
// 准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([])
// 收集新增属性的数据
let attrParams = reactive<Attr>({
  attrName: '',//属性名称
  attrValueList: [],//属性值数组
  categoryId: '', //三级分类id
  categoryLevel: 3, //三级分类
})

// 监听仓库三级分类id变化
watch(() => categoryStore.c3Id, () => {
  attrArr.value = []
  if (!categoryStore.c3Id) return
  getAttr()
})

// 获取已有属性与属性方法
const getAttr = async () => {
  // 获取分类的id
  const { c1Id, c2Id, c3Id } = categoryStore
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    attrArr.value = result.data
  }
}

// 添加属性按钮
const addAttr = () => {
  // 每次点击先清空数据再收集数据
  Object.assign(attrParams, {
    id: '',
    attrName: '',//属性名称
    attrValueList: [],//属性值数组
    categoryId: categoryStore.c3Id, //三级分类id
    categoryLevel: 3, //三级分类
  })
  scene.value = 1
  // 点击按钮收集新增属性的三级分类id
  // attrParams.categoryId = categoryStore.c3Id
}

// 修改属性
const updateAttr = (row: Attr) => {
  scene.value = 1
  // 将已有的属性对象赋值给attrParams
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

// 取消按钮
const cancel = () => {
  scene.value = 0
}

// 添加属性值
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true
  })
  // 获取最后一个el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

// 保存按钮
const save = async () => {
  let result: any = await reqAddOrUpdateAttr(attrParams)
  // 添加属性或者 修改属性成功
  if (result.code == 200) {
    scene.value = 0 //切换场景
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功'
    })
    // 获取全部已有的属性与属性值
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败'
    })
  }
}

// 属性值表单元素失去焦点
const toLook = (row: AttrValue, $index: number) => {
  // 非法清空判断
  if (row.valueName.trim() == '') {
    // 删除对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: "error",
      message: "属性值不能为空"
    })
    return
  }
  // 非法情况2
  let repeat = attrParams.attrValueList.find(item => {
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: "error",
      message: "属性值不能重复"
    })
    return
  }
  row.flag = false
}

// 属性值div点击事件
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

// 删除某一个已有的属性
const deleteAttr = async (attrId: number) => {
  let result = await reqRemoveAttr(attrId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: "删除成功"
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: "删除失败"
    })
  }
}

// 路由组件销毁时,把仓库分类相关的数据清空
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style lang="scss" scoped></style>